<?php

/*
	This file is part of Mandragon.

    Mandragon is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Mandragon is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Mandragon.  If not, see <http://www.gnu.org/licenses/>.
*/

class Forum
{

	private $db_access;

	public function __construct() {
		$this->db_access = new DbAccessor();
	}

	public function fora_get_subfora($parent_id, $menu) {

		if (!is_array($menu[$parent_id]['children']) or !count($menu[$parent_id]['children'])) {
			return array();
		}

		$fora = array();
		
		$sql = $this->db_access->db_query_select(
				array(
						array(), 
						"dir_id, COUNT(DISTINCT ITEM_IN.item_id) AS num_items, COUNT(post_id) AS num_posts, MAX(POST.edit) AS last_edit"), 
				array("(SUB_IN INNER JOIN ITEM_IN ON SUB_IN.sub_id = ITEM_IN.sub_id) LEFT JOIN POST ON ITEM_IN.item_id = POST.item_id", "DUMMY"), 
					"dir_id IN (" . implode(",", $menu[$parent_id]['children']) . ")", "", "", "dir_id");
		$sqlresult = $this->db_access->db_do_query($sql);
		$info = array();
		while ($d = $this->db_access->db_fetch_array($sqlresult)) {
			$info[$d['dir_id']] = $d;
		}
		reset($menu[$parent_id]['children']);
		do {
			$id = current($menu[$parent_id]['children']);
			$p = $id;
			while ($p > 0) {
				$info[$id]['url'] = "/" . $menu[$p]['name'] . $info[$id]['url'];
				$p = $menu[$p]['parent_id'];
			}
			if ($menu[$id]['access'] != "DENY") { // if INHERIT, parent must be allowed to reach this stage
				$fora[] = array_merge($menu[$id], $info[$id]);
			}
		} while (next($menu[$parent_id]['children']));
		
		return $fora;
	}

	public function fora_fetch_multiple($root, $menu, $arr) {

		if (!is_array($menu[$root]['children'])) {
			return array();
		}

		reset($menu[$root]['children']);
		do {
			$id = current($menu[$root]['children']);
			if (is_array($menu[$id]['children']) and count($menu[$id]['children'])) {
				$arr[] = array('fora' => $this->fora_get_subfora($id, $menu), 'title' => $menu[$id]['title']);
			}
		} while (next($menu[$root]['children']));
		
		return $arr;
	}
}

?>
